<template>
  <div>
    <a-row>
      <a-col :span="6">
        <a-form-item
          label="药品名称"
          :wrapper-col="{ span: 16 }"
          name="drugsId"
        >
          <a-select
            v-model:value="queryData.drugsId"
            show-search
            placeholder="请输入药品"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :options="drugsData"
            @search="searchDrugs"
          ></a-select>
        </a-form-item>
      </a-col>
      <a-col :span="6">
        <a-form-item
          v-if="userInfo.empId == 0"
          label="社区名称"
          :wrapper-col="{ span: 16 }"
          name="communityId"
        >
          <a-select
            v-model:value="queryData.communityId"
            show-search
            placeholder="请输入社区"
            :default-active-first-option="false"
            :show-arrow="false"
            :filter-option="false"
            :not-found-content="null"
            :options="communityData"
            @search="searchCommunit"
          ></a-select>
        </a-form-item>
      </a-col>
      <a-col :span="6"> </a-col>

      <a-col :span="6">
        <a-button @click="reset" style="margin-left: 20px">重置</a-button>
        <a-button
          @click="selectPage"
          style="margin: 0 20px; background-color: #6a2c70"
          type="primary"
          >查询</a-button
        >
        <a-button
          @click="inStorage"
          type="primary"
          style="background-color: #b83b5e"
        >
          <template #icon>
            <PlusOutlined />
          </template>
          新增入库</a-button
        >
      </a-col>
    </a-row>

    <a-table
      :loading="isloading"
      :pagination="pagination"
      :columns="libraryCloumns"
      :data-source="liberaryList.data"
      @change="handleTableChange"
      tableLayout="fixed"
    >
      <template #bodyCell="{ index, column, record }">
        <template v-if="column.key === 'index'">
          {{
            queryData.page == 1
              ? index + 1
              : (queryData.page - 1) * queryData.pageSize + index + 1
          }}
        </template>
        <template v-if="column.key === 'drugsName'">
          <a-tooltip>
            <template #title>{{ record?.drugs?.drugsName }}</template>
            <div class="hidden">
              {{ record?.drugs?.drugsName }}
            </div>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'manufacturer'">
          <a-tooltip>
            <template #title>{{ record?.drugs?.manufacturer }}</template>
            <div class="hidden">
              {{ record?.drugs?.manufacturer }}
            </div>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'communityName'">
          <a-tooltip>
            <template #title>{{ record?.community?.communityName }}</template>
            <div class="hidden">
              {{ record?.community?.communityName || '' }}
            </div>
          </a-tooltip>
        </template>
        <template v-if="column.key === 'communityImage'">
          <a-image
            style="border-radius: 8px"
            :width="60"
            :src="record.community?.communityImage"
          />
        </template>
        <template v-if="column.key === 'stock'">
          {{ record?.drugLibrary?.stock }}
        </template>

        <template v-if="column.key === 'action'">
          <a-button
            @click="editDrugLibrary(record)"
            type="primary"
            style="margin-right: 20px; background-color: #f5b017"
            >编辑</a-button
          >
          <a-popconfirm
            title="确认删除此药品数据吗？"
            ok-text="确认"
            cancel-text="取消"
            @confirm="deleteItem(record)"
          >
            <a-button type="primary" style="background-color: #f38181" danger
              >删除</a-button
            >
          </a-popconfirm>
        </template>
      </template>
    </a-table>

    <!-- 抽屉 -->
    <a-drawer
      v-model:open="open"
      class="custom-class"
      root-class-name="root-class-name"
      title="新增入库"
      placement="right"
      width="60%"
      :maskClosable="false"
    >
      <LibraryDrawer v-if="open" @receiveData="receiveData" />
    </a-drawer>

    <!-- 模态框 -->
    <a-modal v-model:open="openModal" title="修改库存" @ok="handleOk">
      <a-form-item
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        label="药品名称"
        name="drugsName"
      >
        <a-input v-model:value="editItem.drugs.drugsName" disabled />
      </a-form-item>

      <a-form-item
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
        label="社区名称"
        name="communityName"
      >
        <a-input v-model:value="editItem.community.communityName" disabled />
      </a-form-item>

      <a-form-item
        label="库存"
        name="stock"
        :label-col="{ span: 4 }"
        :wrapper-col="{ span: 20 }"
      >
        <a-input-number
          :min="1"
          style="width: 100%"
          v-model:value.number="editItem.drugLibrary.stock"
          placeholder="请输入库存"
        />
      </a-form-item>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import LibraryDrawer from './LibraryDrawer.vue'
import { userUserStore } from '@/stores/UserStore'
import { PaginationModel } from '@/api/config/Model'
import { libraryCloumns } from './columns'
import { queryKey } from '@/api/Community/api'
import {
  apiQueryKey,
  apiPageList,
  apiDeleteStore,
  apiEditStore,
} from '@/api/Drugs/api'
import { PlusOutlined } from '@ant-design/icons-vue'
import { ref, reactive, onMounted } from 'vue'
import { LibraryQueryModel } from '@/api/Drugs/model'
import { message } from 'ant-design-vue'

const openModal = ref(false)
const store = userUserStore()
const userInfo: any = ref({})
const communityData: any = ref([])
const queryData = reactive<LibraryQueryModel>({
  page: 1,
  pageSize: 10,
  drugsId: null,
  communityId: null,
})
const pagination = ref<PaginationModel>({
  current: 1,
  total: 100,
  pageSize: 10, //每页中显示10条数据
  pageSizeOptions: ['10', '20', '30'],
})
let timeout: any = ref(null)
let timeout2: any = ref(null)
const drugsData = ref([])
const isloading = ref<boolean>(false)
const liberaryList = reactive<any>({
  data: [],
})
const open = ref<boolean>(false)
const editItem = ref<any>({})
const inStorage = () => {
  open.value = true
}

// 重置查询条件
const reset = () => {
  queryData.drugsId = null
  queryData.page = 1
  queryData.pageSize = 10
  if (userInfo.value.empId == 0) {
    queryData.communityId = null
  }
  // 获取数据
  getPageList()
}

//接受抽屉传递过来的数据
const receiveData = (type: number) => {
  if (type == 3) {
    message.success('入库成功')
  } else {
    message.error('入库失败')
  }
  getPageList()
  open.value = false
}

//查询
const selectPage = () => {
  getPageList()
}

const getPageList = async () => {
  isloading.value = true
  try {
    let res = await apiPageList(queryData)
    pagination.value.current = res.data.current
    pagination.value.pageSize = res.data.size
    pagination.value.total = res.data.total
    liberaryList.data = res.data.records
  } catch (error) {
    message.error('获取药品库数据失败')
  }
  isloading.value = false
}

// 分页改变
const handleTableChange = (page: any) => {
  pagination.value.current = page.current
  pagination.value.pageSize = page.pageSize
  queryData.page = page.current
  queryData.pageSize = page.pageSize
  getPageList()
}

const deleteItem = async (item: any) => {
  await apiDeleteStore({
    drugsId: item.drugs.drugsId,
    communityId: item.community.communityId,
  })
  message.success('删除成功')
  getPageList()
}
//获取药品列表数据
const searchDrugs = (value: any) => {
  if (timeout2.value) {
    clearTimeout(timeout2.value)
    timeout2.value = null
  }

  timeout2.value = setTimeout(async () => {
    let res = await apiQueryKey({
      drugsName: value,
    })
    drugsData.value = res.data.map((ele: any) => {
      return {
        label: ele.drugsName,
        value: ele.drugsId,
        ...ele,
      }
    })
  }, 300)
}

//获取社区列表数据
const searchCommunit = (value: any) => {
  if (timeout.value) {
    clearTimeout(timeout.value)
    timeout.value = null
  }

  timeout.value = setTimeout(async () => {
    let res = await queryKey({
      communityName: value,
    })
    communityData.value = res.data.map((ele: any) => {
      return {
        label: ele.communityName,
        value: ele.communityId,
        ...ele,
      }
    })
  }, 300)
}

//修改库存
const editDrugLibrary = (item: any) => {
  openModal.value = true
  let str = JSON.stringify(item)
  editItem.value = JSON.parse(str)
}

//提交库存
const handleOk = async () => {
  try {
    await apiEditStore({
      drugsId: editItem.value.drugs.drugsId,
      communityId: editItem.value.community.communityId,
      stock: editItem.value.drugLibrary.stock,
    })
    openModal.value = false
    message.success('修改成功！')
    getPageList()
  } catch (error) {
    message.error('修改失败')
  }
}

onMounted(() => {
  //如果不是超级管理员就对社区id进行固定
  userInfo.value = store.employeeInfo
  if (userInfo.value.empId != 0) {
    queryData.communityId = userInfo.value.communityId
  }
  getPageList()
})
</script>

<style lang="less" scoped></style>
